import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, CanActivateChild, CanLoad, Route, RouterStateSnapshot, UrlSegment, UrlTree } from '@angular/router';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';

import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
  private session = sessionStorage;
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(  
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot) {
    this.checkRouter(state.url);
    return true; 
  }
  
  canActivateChild(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return true;
  } 
  
  canLoad(
    route: Route,
    segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
    return true;
  }

  // 判断用户访问权限
  checkRouter(url: string): boolean {
    // 判断用户是否登录
    this.authService.checkLogin();
    if (!this.authService.isLoggedIn) {
      this.router.navigate(['/login']);
      return false;
    }
    
    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;
    const resourceInfo =  JSON.parse(this.session.getItem('resources'));
    for (let i = 0; i < resourceInfo.length; i++) {
      if (resourceInfo[i]['resourceHref'] === url) {
        return true;
      }else if(resourceInfo[i]['resourceHref'].indexOf(url) != -1){
        
      }
    }
    // Navigate to the login page with extras
    const routingUrl: string = '/main/home/' + this.configRouting();
    this.router.navigate([routingUrl]);
    return false;
  }

  /**
   * 获取用户权限
   * 默认路由:
   *  管理员 clue
   *  线索管理员 clue
   *  办案人员  handle
   *  审批人员  approval
   */
  configRouting(): string {
    const permis = JSON.parse(this.session.getItem('roles'))[0]['roleName'];
    if (!permis) {
      alert('无法获取用户权限资源');
      return;
    }
    switch (permis) {
      case '管理员': {
        return 'clue';
      }            break;
      case '线索人员': {
        return 'clue';
      }            break;
      case '办案人员': {
        return 'handle';
      }            break;
      case '审批人员': {
        return 'approval';
      }            break;
      case '局长': {
        return 'approval';
      }
       break;
    }
  }
}
